package com.ruoyi.web.admin.data;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 心跳检测
 *
 * @author 10100
 */
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(HeartbeatHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            // 超时后主动关闭连接
            Object deviceIdAttr = ctx.channel().attr(AttributeKey.valueOf("deviceId")).get();
            String deviceId;
            if (deviceIdAttr == null) {
                deviceId = "";
            } else {
                deviceId = deviceIdAttr.toString();
            }
            log.warn("设备[{}]超时未通信，关闭连接", deviceId);
            DeviceSocketManager.removeClient(deviceId);
            ctx.close();
        }
    }
}